﻿using System;
using System.Windows;
using ButsaLib;
using ButsaLib.Models;
using System.Linq;

namespace ButsaForecast.Dialogs
{
	/// <summary>
	/// Interaction logic for NewSnapshot.xaml
	/// </summary>
	public partial class NewSnapshotDialog
	{
		private ForecastSnapshot _forecastSnapshot;

		public NewSnapshotDialog()
		{
			InitializeComponent();

			_forecastSnapshot = new ForecastSnapshot { SnapshotDate = DateTime.Now };

			FormGrid.DataContext = _forecastSnapshot;
		}

		public ForecastSnapshot GetCreatedForecastSnapshot()
		{
			return _forecastSnapshot;
		}

		private void OkButtonClick(object sender, RoutedEventArgs e)
		{
			using (ButsaDbContext dbContext = new ButsaDbContext())
			{
				var dbForecastSnapshot = dbContext.ForecastSnapshots
					.FirstOrDefault(item => item.SnapshotName == _forecastSnapshot.SnapshotName);
				if (dbForecastSnapshot != null)
				{
					dbContext.ForecastSnapshots.Remove(dbForecastSnapshot);
					dbContext.SaveChanges();
				}

				_forecastSnapshot = dbContext.ForecastSnapshots.Add(_forecastSnapshot);
				var recordsAffected = dbContext.SaveChanges();
				if (recordsAffected == 1)
					DialogResult = true;
			}
		}

		private void CancelButtonClick(object sender, RoutedEventArgs e)
		{
			DialogResult = false;
		}
	}
}
